package com.gexiaobao.pigeon.ui.activity

//import kotlinx.android.synthetic.main.fragment_game_result.smartTableResult
//import kotlinx.android.synthetic.main.fragment_game_result.tv_race_result_no_data
import android.annotation.SuppressLint
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import com.bin.david.form.core.SmartTable
import com.bin.david.form.core.TableConfig
import com.bin.david.form.data.CellInfo
import com.bin.david.form.data.format.bg.BaseCellBackgroundFormat
import com.bin.david.form.data.style.FontStyle
import com.bin.david.form.data.style.LineStyle
import com.bin.david.form.data.table.MapTableData
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.GameResultPigeonInfoResponse
import com.gexiaobao.pigeon.app.model.bean.RaceResultResponse
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.util.WxShareUtils
import com.gexiaobao.pigeon.databinding.ActivityGameResultBinding
import com.gexiaobao.pigeon.ui.dialog.RxDialogGameResultMore
import com.gexiaobao.pigeon.ui.dialog.RxDialogPageTurning
import com.gexiaobao.pigeon.ui.fragment.mine.organization.video.ActivityPlayBack
import com.gexiaobao.pigeon.ui.fragment.mine.pigeon.activity.ActivityForceAnalysis
import com.gexiaobao.pigeon.ui.fragment.mine.pigeon.activity.ActivityVideoPlayer
import com.gexiaobao.pigeon.ui.race.RaceViewModel
import com.google.gson.Gson
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import me.hgj.jetpackmvvm.util.startActivity
import me.jessyan.autosize.internal.CustomAdapt
import org.json.JSONArray
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Date
import kotlin.math.ceil

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 14:52
 * @Describe    : 比赛结果

 */
class ActivityGameResult : BaseActivity<RaceViewModel, ActivityGameResultBinding>(), CustomAdapt {
    private lateinit var dialog: RxDialogGameResultMore
    private var operation: String = ""
    private var landScreenBoolean = false
    private var landScreenFloat: Float = 580.0F
    private var landScreenFloatHW: Float = 420.0F
    private var landScreenFloatNok: Float = 410.0F
    private var landScreenFloatS: Float = 760.0F
    private var landScreenFloatM: Float = 1080.0F

    private var mPassId = ""
    private var mRaceId = ""
    private var mOrgId = ""
    private var pageSize = 50
    private var pageNo = 1
    private var memberCode = ""
    private var mRingId = ""
    private var mFosterName = ""
    private var totalPage = 0
    private var mType = ""
    private var pressedSelf = false

    lateinit var data: SmartTable<RaceResultResponse.PassResultBody>

    private var ringId = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        StatusBarUtil.setLightMode(this)
    }

    override fun initView(savedInstanceState: Bundle?) {
        setStatusBarTranslucent()
        mDatabind.viewmodel = mViewModel
        mDatabind.etSearch.hint = "请输入鸽主姓名"
        mDatabind.viewmodel = mViewModel
        val title = intent.getStringExtra("title").toString()
        mViewModel.title.set(title)
        mPassId = intent.getIntExtra("passId", 0).toString()
        mType = intent.getStringExtra("type").toString()
        if (intent.hasExtra("raceId")) {
            mRaceId = intent.getIntExtra("raceId", 0).toString()
        }

        if (title.isEmpty() && intent.hasExtra("memberNum")) {
            memberCode = intent.getStringExtra("memberNum").toString()
        }
        initSmartTable()

        showLoading(getString(R.string.loading))
        mViewModel.getPassResultWeb(
            mPassId,
            pageSize.toString(),
            pageNo.toString(),
            "",
            memberCode,
            mRingId,
            mFosterName,
            ""
        )
        mDatabind.etSearch.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH ->
                    searchResult()

                else -> {}
            }
            false
        }
        mDatabind.etSearch.addTextChangedListener {
            if (it!!.isEmpty()) {
                pageNo = 1
                memberCode = ""
                mFosterName = ""
                showLoading(getString(R.string.loading))
                mViewModel.getPassResultWeb(
                    mPassId,
                    pageSize.toString(),
                    pageNo.toString(),
                    "",
                    memberCode,
                    mRingId,
                    mFosterName,
                    ""
                )
            }
        }
    }

    private fun initSmartTable() {
        data = mDatabind.smartTableResult as SmartTable<RaceResultResponse.PassResultBody>
        val fontStyle = FontStyle(this, 22, ContextCompat.getColor(this, R.color.black))
        val contentStyle = FontStyle(this, 19, ContextCompat.getColor(this, R.color.comm_text_gray))
        val lineStyle = LineStyle()
        lineStyle.color = ContextCompat.getColor(this, R.color.dedede)
        data.config.columnTitleStyle = fontStyle
        data.config.contentStyle = contentStyle
        data.config.setHorizontalPadding(20)
            .setVerticalPadding(15)
            .setSequenceHorizontalPadding(20)
            .setSequenceVerticalPadding(40)
            .setShowTableTitle(false) // 去除标题
            .setFixedFirstColumn(true) //第一行作废
            .setShowXSequence(false)
            .setShowYSequence(false)
            .isFixedYSequence = true
    }

    private fun searchResult() {
        hideSoftKeyboard(this)
        when {
            mViewModel.etSearchResult.get().isEmpty() -> showMessage("请输入要查询的内容")
            else -> {
                pageNo = 1
                memberCode = ""
                mFosterName = mViewModel.etSearchResult.get()
                showLoading(getString(R.string.loading))
                mViewModel.getPassResultWeb(
                    mPassId,
                    pageSize.toString(),
                    pageNo.toString(),
                    "",
                    memberCode,
                    mRingId,
                    mFosterName,
                    mViewModel.etSearchResult.get()
                )
            }
        }

    }

    @SuppressLint("SimpleDateFormat")
    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.ivMatchResultBack,
            mDatabind.tvMatchResultTitle,
            mDatabind.raceResultPageAll,
            mDatabind.raceResultPageMine,
            mDatabind.raceResultPageRefresh,
            mDatabind.raceResultPageFirst,
            mDatabind.raceResultPageBefore,
            mDatabind.raceResultPageNext,
            mDatabind.raceResultPageLast,
            mDatabind.tvShare,
            mDatabind.tvThrough
        ) {
            when (it) {
                mDatabind.tvThrough -> showDialogPageTurning()
                mDatabind.tvShare -> {
                    val url = Constant.SHARE_URL + "/race?o=$mOrgId&r=$mRaceId&p=$mPassId"
                    try {
                        val sdf = SimpleDateFormat("yyyy-MM-dd")
                        val dateFormatString = sdf.format(Date(System.currentTimeMillis()))
                        val bmp = BitmapFactory.decodeResource(resources, R.mipmap.app_icon_)
                        WxShareUtils.shareWeb(
                            this, Constant.WX_APP_ID,
                            url, "鸽小宝信鸽竞翔-比赛结果", "" + dateFormatString,
                            bmp
                        )
                    } catch (e: Exception) {
                        e.printStackTrace()
                        LogUtils.debugInfo("获取比赛结果信息失败")
                    }
                }

                mDatabind.ivMatchResultBack, mDatabind.tvMatchResultTitle -> {
                    finish()
                }

                mDatabind.raceResultPageAll -> {
                    pageNo = 1
                    memberCode = ""
                    mFosterName = ""
                    mViewModel.etSearchResult.set("")
                    showLoading(getString(R.string.loading))
                    mViewModel.getPassResultWeb(
                        mPassId,
                        pageSize.toString(),
                        pageNo.toString(),
                        "",
                        memberCode,
                        mRingId,
                        mFosterName,
                        ""
                    )
                }

                mDatabind.raceResultPageMine -> {
                    pressedSelf = true
                    pageNo = 1
                    showLoading(getString(R.string.loading))
                    mViewModel.getMemberNum(mPassId)
                }

                mDatabind.raceResultPageRefresh -> {
                    showLoading(getString(R.string.loading))
                    mViewModel.getPassResultWeb(
                        mPassId,
                        pageSize.toString(),
                        pageNo.toString(),
                        "",
                        memberCode,
                        mRingId,
                        mFosterName,
                        mViewModel.etSearchResult.get()
                    )
                }

                mDatabind.raceResultPageFirst -> {//首页
                    if (pageNo == 1) {
                        RxToast.showToast("这已经是第一页了")
                        return@setOnclickNoRepeat
                    }
                    pageNo = 1
                    showLoading(getString(R.string.loading))
                    mViewModel.getPassResultWeb(
                        mPassId,
                        pageSize.toString(),
                        pageNo.toString(),
                        "",
                        memberCode,
                        mRingId,
                        mFosterName,
                        mViewModel.etSearchResult.get()
                    )
                }

                mDatabind.raceResultPageBefore -> {
                    if (pageNo == 1) {
                        RxToast.showToast("这已经是第一页了")
                        return@setOnclickNoRepeat
                    }
                    pageNo--
                    showLoading(getString(R.string.loading))
                    mViewModel.getPassResultWeb(
                        mPassId,
                        pageSize.toString(),
                        pageNo.toString(),
                        "",
                        memberCode,
                        mRingId,
                        mFosterName,
                        mViewModel.etSearchResult.get()
                    )
                }

                mDatabind.raceResultPageNext -> {
                    if (pageNo == totalPage) {
                        RxToast.showToast("这已经是最后一页了")
                        return@setOnclickNoRepeat
                    }
                    pageNo++
                    showLoading(getString(R.string.loading))
                    mViewModel.getPassResultWeb(
                        mPassId,
                        pageSize.toString(),
                        pageNo.toString(),
                        "",
                        memberCode,
                        mRingId,
                        mFosterName,
                        mViewModel.etSearchResult.get()
                    )
                }

                mDatabind.raceResultPageLast -> {
                    if (pageNo == totalPage) {
                        RxToast.showToast("这已经是最后一页了")
                        return@setOnclickNoRepeat
                    }
                    pageNo = totalPage
                    showLoading(getString(R.string.loading))
                    mViewModel.getPassResultWeb(
                        mPassId,
                        pageSize.toString(),
                        totalPage.toString(),
                        "",
                        memberCode,
                        mRingId,
                        mFosterName,
                        mViewModel.etSearchResult.get()
                    )
                }
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 获取单用户下探视棚号列表  */
        mViewModel.visitMemberResult.observe(this) {
            if (it.list.isEmpty()) {
                showMessage("您还未成为该场赛事会员，暂无权查看归巢视频")
                return@observe
            }
            if (::dialog.isInitialized) dialog.dismiss()
            startActivity<ActivityPlayBack>("ringId" to ringId, "passId" to mPassId.toInt(), "title" to "归巢视频", "type" to 2)
        }
        mViewModel.raceResultResult.observe(this) {
            dismissLoading()
            if (it != null) {
                val data = Gson().toJson(it)
                val result = JSONObject(data.toString())
                mOrgId = result.getInt("orgId").toString()
                mRaceId = result.getInt("raceId").toString()
                mViewModel.percentage.set("(" + result.getString("bkPercent") + ")")
                if (mType == "race") {
                    mViewModel.signUpPigeonNum.set(
                        "集:" + result.getInt("gPyCnt").toString() + "舍" + result.getInt("gCnt")
                            .toString() + "羽"
                    )
                } else {
                    mViewModel.signUpPigeonNum.set(
                        "报:" + result.getInt("gPyCnt").toString() + "舍" + result.getInt("gCnt")
                            .toString() + "羽"
                    )
                }
                mViewModel.homingPigeonNum.set(
                    "归:" + result.getInt("bkPyCnt").toString() + "舍" + result.getInt("bkCnt")
                        .toString() + "羽"
                )

                val passResultHead = result.getJSONArray("passResultHead")
                val passResultBody = result.getJSONArray("passResultBody")

                if (passResultBody.length() == 0) {
                    mViewModel.raceResultPageNo.set("0/0")
                    mDatabind.tvRaceResultNoData.visibility = View.VISIBLE
                    mDatabind.smartTableResult.visibility = View.GONE
                    if (pressedSelf) {
                        RxToast.showToast("未查询到本人的比赛结果")
                    } else {
                        RxToast.showToast("未生成比赛结果")
                    }
                } else {
                    mDatabind.tvRaceResultNoData.visibility = View.GONE
                    mDatabind.smartTableResult.visibility = View.VISIBLE
                    totalPage = ceil(SettingUtil.div(result.getInt("total").toDouble(), 50.00, 2)).toInt()//取整
                    setSmartTableData(passResultHead, passResultBody)
                    mViewModel.raceResultPageNo.set("$pageNo/$totalPage")
                }
            }
        }

        mViewModel.memberNumResult.observe(this) {
            if (it != null) {
                pageNo = 1
                mFosterName = ""
                mViewModel.etSearchResult.set(it.memberNum)
                memberCode = it.memberNum
                if (memberCode.isEmpty()) {
                    RxToast.warning("非本场赛事会员")
                    return@observe
                }
                showLoading(getString(R.string.loading))
                mViewModel.getPassResultWeb(
                    mPassId,
                    pageSize.toString(),
                    pageNo.toString(),
                    "",
                    memberCode,
                    mRingId,
                    mFosterName,
                    ""
                )
            }
        }
    }

    private fun setSmartTableData(passResultHead: JSONArray, passResultBody: JSONArray) {
        val list1 = ArrayList<Any>()
        var value = ""
        for (i in 0 until passResultBody.length()) {
            val map = LinkedHashMap<String, String>()
            for (j in 0 until passResultHead.length()) {
                val dataHead = passResultHead[j].toString()
                val dataBody = passResultBody[i].toString()
                val key = JSONObject(dataHead).getString("title")
                val valueStr = JSONObject(dataHead).getString("key")
                value = JSONObject(dataBody).getString(valueStr)
                when (valueStr) {
                    "ringId" -> {
                        value = Util.check2FormatRingId(value)
                    }

                    "homingTime", "lonLat" -> {
                        value = value.replace(" ", "\n")
                    }

                    "operation" -> {
                        operation = JSONObject(dataBody).getString("operation")
                        value = "更多"
                    }
                }
                map[key] = value
            }
            list1.add(map)
        }
        val mapData = MapTableData.create("比赛成绩", list1)
        mapData.columns[0].isFixed = true
        mapData.columns[1].isFixed = true
        mapData.columns[3].isFixed = true
        mDatabind.smartTableResult.tableData = mapData

        data.config.contentCellBackgroundFormat = object : BaseCellBackgroundFormat<CellInfo<*>>() {
            override fun getBackGroundColor(t: CellInfo<*>): Int {
                return TableConfig.INVALID_COLOR
            }

            override fun getTextColor(t: CellInfo<*>): Int {
                return when (t.column.columnName) {
                    "寄养人", "棚号", "操作" -> {
                        ContextCompat.getColor(appContext, R.color.bg_light_bllue)
                    }

                    else -> {
                        super.getTextColor(t)
                    }
                }
            }
        }
        data.tableData?.setOnItemClickListener { column, value, t, col, row ->
            if ("寄养人" == column.columnName) {
                if (t != null) {
                    if (!TextUtils.isEmpty(t.toString())) {
                        mFosterName = value
                        pageNo = 1
                        memberCode = ""
                        mViewModel.etSearchResult.set(mFosterName)
                        showLoading(getString(R.string.loading))
                        mViewModel.getPassResultWeb(
                            mPassId,
                            pageSize.toString(),
                            pageNo.toString(),
                            "",
                            memberCode,
                            mRingId,
                            mFosterName,
                            mViewModel.etSearchResult.get()
                        )
                    }
                }
            }
            if ("棚号" == column.columnName) {
                if (t != null) {
                    if (!TextUtils.isEmpty(t.toString())) {
                        mFosterName = ""
                        pageNo = 1
                        memberCode = value
                        mViewModel.etSearchResult.set(memberCode)
                        showLoading(getString(R.string.loading))
                        mViewModel.getPassResultWeb(
                            mPassId,
                            pageSize.toString(),
                            pageNo.toString(),
                            "",
                            memberCode,
                            mRingId,
                            mFosterName,
                            mViewModel.etSearchResult.get()
                        )
                    }
                }
            }
            if ("操作" == column.columnName) {
                if (t != null) {
                    if (!TextUtils.isEmpty(t.toString())) {
                        try {
                            val info = passResultBody[row].toString()
                            val bean = Gson().fromJson(info, GameResultPigeonInfoResponse::class.java)
                            if (bean != null) {
                                showMoreFunctionDialog(bean)
                            } else {
                                RxToast.warning("数据返回异常")
                            }
                        } catch (e: NullPointerException) {
                            e.printStackTrace()
                        }
                    }
                }
            }
        }
    }

    private fun showMoreFunctionDialog(bean: GameResultPigeonInfoResponse) {
        ringId = bean.ringId
        val videoStatus = if (bean.operation == null) {
            false
        } else {
            bean.operation.videoStatus == 2
        }
        val picStatus = if (bean.operation == null) {
            false
        } else {
            bean.operation.picStatus == 2
        }

        dialog = RxDialogGameResultMore(this)
        dialog.setHiddenVideo(videoStatus)
        dialog.setHiddenPicture(picStatus)
        dialog.setPictureListener {

        }
        dialog.setVideoListener {
            mViewModel.getVisitMemberNoList(mRaceId)
        }
        dialog.setRecordListener {
            startActivity<ActivityForceAnalysis>(
                "pigeonId" to bean.operation!!.pigeonId.toString(),
                "ringId" to bean.ringId,
                "raceId" to bean.operation.raceId,
                "raceType" to bean.operation.passType
            )
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun showDialogPageTurning() {
        var pageNumber: Int
        val dialog = RxDialogPageTurning(this)
        dialog.setTitle("选择要查看的页码\n共： $totalPage  页")
        dialog.setPlusListener {
            pageNumber = if (dialog.getCurrentPage().isEmpty()) {
                1
            } else {
                dialog.getCurrentPage().toInt()
            }
            if (pageNumber > totalPage) {
                RxToast.warning("您的输入已超出总页码")
                return@setPlusListener
            }
            if (pageNumber == totalPage) {
                RxToast.warning("当前已经是最后一页")
                return@setPlusListener
            }
            pageNumber++
            dialog.setCurrentPage(pageNumber.toString())
        }
        dialog.setMinusListener {
            pageNumber = if (dialog.getCurrentPage().isEmpty()) {
                1
            } else {
                dialog.getCurrentPage().toInt()
            }

            if (pageNumber == 1) {
                RxToast.warning("当前已经是第一页")
                return@setMinusListener
            }
            pageNumber--
            dialog.setCurrentPage(pageNumber.toString())
        }
        dialog.setSureListener {
            pageNo = if (dialog.getCurrentPage().isEmpty()) {
                1
            } else {
                dialog.getCurrentPage().toInt()
            }
            if (pageNo > totalPage) {
                RxToast.warning("您的输入已超出总页码")
                return@setSureListener
            }
            mViewModel.raceResultPageNo.set("$pageNo/$totalPage")
            showLoading(getString(R.string.loading))
            mViewModel.getPassResultWeb(
                mPassId,
                pageSize.toString(),
                pageNo.toString(),
                "",
                memberCode,
                mRingId,
                mFosterName,
                mViewModel.etSearchResult.get()
            )
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    override fun isBaseOnWidth(): Boolean {
        return if (Build.MANUFACTURER == "realme" || Build.MANUFACTURER == "vivo" || Build.MANUFACTURER == "OPPO"
            || Build.MANUFACTURER == "HUAWEI" || Build.MANUFACTURER == "HMD Global"
        ) {
            landScreenBoolean
        } else {
            !landScreenBoolean
        }
    }

    override fun getSizeInDp(): Float {
        return when (Build.MANUFACTURER) {
            "realme", "vivo", "OPPO" -> {
                landScreenFloat
            }

            "HUAWEI" -> {
                landScreenFloatHW
            }

            "HMD Global" -> {
                landScreenFloatNok
            }

            "Xiaomi" -> {
                landScreenFloatM
            }

            else -> {
                landScreenFloatS
            }
        }
    }
}